<template>
  <div class="p-6 space-y-4">
    <el-card shadow="never" class="rounded-lg">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="onSearch">
        <el-row :gutter="12" align="bottom">
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="设备位号或名称">
              <el-input v-model="filters.keyword" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="负责人">
              <el-select v-model="filters.principal" placeholder="请选择" clearable>
                <el-option v-for="p in principalOptions" :key="p" :label="p" :value="p" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="计划巡检时间">
              <el-date-picker v-model="filters.planTime" type="date" placeholder="选择日期" clearable class="w-full" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="4" class="flex justify-end items-end">
            <el-button type="primary" :loading="queryLoading" @click="onSearch">
              <el-icon class="mr-1"><Search /></el-icon>
              查询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="设备位号" prop="code" min-width="120" />
          <el-table-column label="设备名称" prop="name" min-width="140" />
          <el-table-column label="计划巡检时间" prop="planTime" min-width="150" />
          <el-table-column label="实际巡检时间" prop="actualTime" min-width="150" />
          <el-table-column label="是否漏检" width="110" align="center">
            <template #default="scope">
              {{ scope.row.missed ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column label="设备状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.status)">{{ scope.row.statusLabel }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所属部门" prop="department" min-width="120" />
          <el-table-column label="执行人" prop="executor" min-width="120" />
          <el-table-column label="负责人" prop="principal" min-width="120" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-link type="danger" @click="onDelete(scope.row)">删除</el-link>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'

interface InspectionRecord {
  id: number
  code: string
  name: string
  planTime: string
  actualTime: string
  missed: boolean
  status: string
  statusLabel: string
  department: string
  executor: string
  principal: string
}

const principalOptions = ['王伟', '李娜', '张敏', '刘洋', '陈杰', '杨静', '黄磊', '周玲', '吴涛', '赵敏']

const filters = reactive({
  keyword: '',
  principal: '',
  planTime: '' as any,
})

const queryLoading = ref(false)
const tableLoading = ref(false)

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
})

const statusTagMap: Record<string, string> = {
  normal: 'primary',
  attention: 'warning',
  stop: 'info',
}
const statusTagType = (s: string) => statusTagMap[s] ?? 'info'

const allRecords = ref<InspectionRecord[]>([])

const mockInit = () => {
  const codes = ['VO101B', 'VO102A', 'PX305', 'HT450', 'SA600', 'IB220', 'EL330']
  const names = ['主反应釜', '备用反应釜', '冷却循环泵', '换热器', '安全阀', '仪表盘', '电机']
  const departments = ['生产部门', '设备部', '安环部', '工艺部']
  const executors = ['陈强', '李静', '王磊', '赵蕾', '周涛', '孙悦']
  const principals = principalOptions
  const statusList: Array<[string, string]> = [
    ['normal', '正常'],
    ['attention', '关注'],
    ['stop', '停止'],
  ]
  const list: InspectionRecord[] = []
  let id = 1
  const n = 13 // 固定条数
  for (let i = 0; i < n; i++) {
    const code = codes[i % codes.length]
    const name = names[i % names.length]
    const department = departments[i % departments.length]
    const executor = executors[i % executors.length]
    const principal = principals[i % principals.length]
    const [status, statusLabel] = statusList[i % statusList.length]
    const month = (i % 9) + 1
    const planTime = `2024-${String(month).padStart(2, '0')}-05 09:00`
    const actualTime = `2024-${String(month).padStart(2, '0')}-05 ${String(8 + (i % 5)).padStart(2, '0')}:30`
    const missed = i % 7 === 0
    list.push({ id: id++, code, name, planTime, actualTime, missed, status, statusLabel, department, executor, principal })
  }
  allRecords.value = list
}

const tableData = ref<InspectionRecord[]>([])

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1

const formatDate = (d: any) => {
  if (!d) return ''
  const dt = new Date(d)
  const y = dt.getFullYear()
  const m = String(dt.getMonth() + 1).padStart(2, '0')
  const da = String(dt.getDate()).padStart(2, '0')
  return `${y}-${m}-${da}`
}

const applyFilter = () => {
  const k = filters.keyword.trim()
  const pDate = filters.planTime ? formatDate(filters.planTime) : ''
  return allRecords.value.filter((r) => {
    const matchK = k ? r.code.includes(k) || r.name.includes(k) : true
    const matchP = filters.principal ? r.principal === filters.principal : true
    const matchPlan = pDate ? r.planTime.startsWith(pDate) : true
    return matchK && matchP && matchPlan
  })
}

const refreshTable = (list: InspectionRecord[]) => {
  pagination.total = list.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  tableData.value = list.slice(start, start + pagination.pageSize)
}

const fetchList = async (btn = true) => {
  if (btn) queryLoading.value = true
  tableLoading.value = true
  try {
    await new Promise((r) => setTimeout(r, 200))
    const filtered = applyFilter()
    refreshTable(filtered)
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试')
  } finally {
    tableLoading.value = false
    queryLoading.value = false
  }
}

const onSearch = () => {
  pagination.currentPage = 1
  fetchList()
}
const onSizeChange = (s: number) => {
  pagination.pageSize = s
  pagination.currentPage = 1
  fetchList(false)
}
const onPageChange = (p: number) => {
  pagination.currentPage = p
  fetchList(false)
}

const onDelete = async (row: InspectionRecord) => {
  try {
    await ElMessageBox.confirm(`确认删除设备“${row.code}”的巡检记录？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    tableLoading.value = true
    await new Promise((r) => setTimeout(r, 200))
    allRecords.value = allRecords.value.filter((x) => x.id !== row.id)
    if ((pagination.currentPage - 1) * pagination.pageSize >= allRecords.value.length && pagination.currentPage > 1) pagination.currentPage -= 1
    await fetchList(false)
    ElMessage.success('删除成功')
  } catch (e: any) {
    if (e !== 'cancel' && e !== 'close') ElMessage.error('删除失败，请稍后重试')
  } finally {
    tableLoading.value = false
  }
}

onMounted(async () => {
  mockInit()
  await fetchList(false)
})
</script>
